package cn.iotnc.camera.ui.main

import android.content.res.Configuration
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.iotnc.camera.databinding.ActivityMainBinding
import cn.iotnc.camera.databinding.DialogAddCameraBinding
import cn.iotnc.camera.model.CameraBean
import cn.iotnc.camera.ui.display.DisplayActivity
import cn.iotnc.camera.ui.widget.StateLayout
import cn.iotnc.camera.util.*
import com.hi.dhl.binding.viewbind
import dagger.hilt.android.AndroidEntryPoint
import io.cabriole.decorator.ColumnProvider
import io.cabriole.decorator.GridMarginDecoration
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import org.jetbrains.anko.*

@AndroidEntryPoint
class MainActivity : AppCompatActivity(), AnkoLogger {
    private val viewModel by viewModels<MainViewModel>()
    private val binding by viewbind<ActivityMainBinding>()
    private lateinit var stateLayout: StateLayout
    private val cameraManagerAdapter: CameraManagerAdapter by lazy {
        CameraManagerAdapter()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setSupportActionBar(binding.toolBar)
        binding.vm = viewModel

        stateLayout = StateLayout(this)
            .retry { viewModel.startSearch() }
            .wrap(binding.swipeRefreshLayout)
            .showLoading()

        binding.recyclerView.apply {
            hasFixedSize()
            itemAnimator = DefaultItemAnimator()
            layoutManager = GridLayoutManager(
                context,
                if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) 5 else 3
            )
            addItemDecoration(
                GridMarginDecoration(
                    margin = dip(8),
                    columnProvider = object : ColumnProvider {
                        override fun getNumberOfColumns(): Int =
                            if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) 5 else 3
                    },
                    orientation = RecyclerView.VERTICAL
                )
            )
            adapter = cameraManagerAdapter
        }

        binding.fab.clicks().onEach {
            val dialogBinding = DialogAddCameraBinding.inflate(layoutInflater)
            alert {
                title = "添加相机"
                customView = dialogBinding.root
                cancelButton { }
                okButton {
                    val ip = dialogBinding.editIp.text
                    if (ip.isNullOrBlank() || !ip.toString().checkIp()) {
                        toast("请输入正确的ip")
                        return@okButton
                    }
                    viewModel.addCamera(CameraBean(ip.toString(), "", "", "jpg"))
                    //cameraManagerAdapter.addData(CameraBean(ip.toString(), "", "jpg"))
                    //stateLayout.showContent()
                }
            }.show()
        }.launchIn(lifecycleScope)

        cameraManagerAdapter.setOnItemClickListener { adapter, _, position ->
            DisplayActivity.startDisplay(this, adapter.data as MutableList<CameraBean>, position)
        }

        viewModel.searchStateLiveData.observe({ lifecycle }) {
            if (it) {
                binding.fab.gone()
            } else {
                binding.fab.visible()
            }
        }

        viewModel.cameraDeviceLiveData.observe({ lifecycle }) {
            binding.swipeRefreshLayout.isRefreshing = false
            if (it.isNullOrEmpty()) {
                stateLayout.showError()
            } else {
                stateLayout.showContent()
                cameraManagerAdapter.replaceData(it)
            }
        }
        if (viewModel.cameraDeviceLiveData.value == null) {
            viewModel.startSearch()
        }
    }

}